<template>
  <div>
    <a-row style="margin-top:16px">
      <a-col :span="5">
        <a-card class="br mh">
          <div class="title-control">
            <h3>选择审计资产</h3>
            <a-button v-if="TreeSwitching" class="yellow_search_btn" @click="handleSwich">切换</a-button>
          </div>
          <a-spin v-if="treeLoading" />
          <a-tree
            v-if="departTree.length > 0 && !treeLoading"
            :treeData="departTree"
            draggable
            @dragstart="handledragstart($event)"
          >
            <a-icon slot="switcherIcon" type="down" />
          </a-tree>
        </a-card>
      </a-col>
      <a-col :span="19" class="cogfig-box">
        <a-card class="br">
          <h3>审计资产</h3>
          <div class="audit-box">
            <div
              class="primary-table"
              @drop.prevent="dropHandler($event, 1)"
              @dragover.prevent="dragoverHandler($event, 1)"
            >
              <DargEmpty v-if="primaryData.isEmpty" class="primary-empty"></DargEmpty>
              <ItemBox
                v-else
                :isPrimary="true"
                :itemData="primaryData.data"
                @Delete="handleDelete"
                @StructureCheck="handleStructureCheck"
                @DataCheck="handleDataCheck"
                @TreeCheck="handleTreeCheck"
              ></ItemBox>
            </div>
            <div class="relative1">
              <div class="title-box" @click="handlerClick">
                <a-tooltip placement="topLeft" overlayClassName="bgc_tooltip1">
                  <template slot="title">
                    <span>{{ primaryData.data.title }}</span>
                  </template>
                  <span class="box-card-title">{{ primaryData.data.title }}</span>
                </a-tooltip>
                <a-tooltip placement="topLeft" overlayClassName="bgc_tooltip1">
                  <template slot="title">
                    <span>{{ primaryFiled }}</span>
                  </template>
                  <span class="box-card-title">{{ primaryFiled }}</span>
                </a-tooltip>
                <a-tooltip placement="topLeft" overlayClassName="bgc_tooltip1">
                  <template slot="title">
                    <span>主表附表关联字段</span>
                  </template>
                  <a-icon type="swap" class="swap" />
                </a-tooltip>
                <a-tooltip placement="topLeft" overlayClassName="bgc_tooltip1">
                  <template slot="title">
                    <span>{{ subTitles }}</span>
                  </template>
                  <span class="box-card-title">{{ subTitles }}</span>
                </a-tooltip>
                <a-tooltip placement="topLeft" overlayClassName="bgc_tooltip1">
                  <template slot="title">
                    <span>{{ subFiled }}</span>
                  </template>
                  <span class="box-card-title">{{ subFiled }}</span>
                </a-tooltip>
              </div>
            </div>
            <div class="sub-table">
              <div
                :key="index"
                v-for="(item, index) in subTableData"
                @drop.prevent="dropHandler($event, 2, index)"
                @dragover.prevent="dragoverHandler($event, 2, index)"
              >
                <DargEmpty v-if="item.isEmpty" class="sub-empty"></DargEmpty>
                <ItemBox
                  v-else
                  :itemData="item.data"
                  @Delete="handleDelete"
                  @StructureCheck="handleStructureCheck"
                  @DataCheck="handleDataCheck"
                  @TreeCheck="handleTreeCheck"
                ></ItemBox>
              </div>
            </div>
          </div>
        </a-card>
        <a-card class="br" style="margin-top:16px">
          <h3>指标参数</h3>
          <IndicatorTable
            :dataSource="IndicatorDataSource"
            :columns="columns1"
            @DropHandler="DropHandler('IndicatorDataSource', 'cacheIndicatorDataSource')"
            @Edit="id => handleEdit('IndicatorDataSource', id)"
            @DataChange="(id, value, col) => handleDataChange('IndicatorDataSource', id, value, col)"
            @SaveData="id => handleSaveData('IndicatorDataSource', 'cacheIndicatorDataSource', id)"
            @Delete="id => handleDeleteRow('IndicatorDataSource', id)"
            @CancelData="id => handleCancelData('IndicatorDataSource', 'cacheIndicatorDataSource', id)"
            @Up="id => handleUp('IndicatorDataSource', id)"
            @Down="id => handleDown('IndicatorDataSource', id)"
          />
        </a-card>
        <a-card class="br" style="margin-top:16px">
          <h3>输出指标</h3>
          <OutputTable
            :dataSource="OutputDataSource"
            :columns="columns2"
            @DropHandler="DropHandler('OutputDataSource', 'cacheOutputDataSource')"
            @Edit="id => handleEdit('OutputDataSource', id)"
            @DataChange="(id, value, col) => handleDataChange('OutputDataSource', id, value, col)"
            @SaveData="id => handleSaveData('OutputDataSource', 'cacheOutputDataSource', id)"
            @Delete="id => handleDeleteRow('OutputDataSource', id)"
            @CancelData="id => handleCancelData('OutputDataSource', 'cacheOutputDataSource', id)"
            @Up="id => handleUp('OutputDataSource', id)"
            @Down="id => handleDown('OutputDataSource', id)"
          />
        </a-card>
      </a-col>
    </a-row>
    <div class="button-control">
      <a-button @click="onReset" class="yellow_search_btn">清空</a-button>
      <a-button @click="onSave" class="clear_btn">保存</a-button>
      <a-button @click="onRun" class="clear_btn">执行</a-button>
    </div>
    <CheckOrganModal ref="CheckOrganModal" :urlList="url.DataStructure" @Ok="handleOk"></CheckOrganModal>
  </div>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction, deleteAction, postAction } from '@/api/manage'
import IndicatorTable from './IndicatorTable.vue'
import OutputTable from './OutputTable'
import DargEmpty from './DargEmpty'
import ItemBox from './ItemBox'
import CheckOrganModal from './CheckOrganModal'

import { columns1, columns2, columns3 } from '../columns'
export default {
  mixins: [JeecgListMixin],
  props: ['isReset'],
  components: {
    IndicatorTable,
    OutputTable,
    DargEmpty,
    ItemBox,
    CheckOrganModal
  },
  data() {
    return {
      columns1: columns1(),
      columns2: columns2(),
      columns3: columns3(),
      subTableData: [
        {
          data: {},
          isEmpty: true
        },
        {
          data: {},
          isEmpty: true
        },
        {
          data: {},
          isEmpty: true
        },
        {
          data: {},
          isEmpty: true
        }
      ],
      primaryData: {
        data: {},
        isEmpty: true
      },
      IndicatorDataSource: [],
      cacheIndicatorDataSource: [],
      OutputDataSource: [],
      cacheOutputDataSource: [],
      stepNum: {},
      url: {
        // 树数据
        treeUrl: '/sjzcml/dataModelTopic/queryModelTopicTree',
        //数据查看
        DataRelation: '/sjzcml/dataModelTopic/queryDataRelation',
        //检查结构
        DataStructure: '/sjzcml/dataModelTopic/queryDataStructure',
        //  保存接口
        saveCustom: '/custom/saveCustom',
        //  查询配置
        queryCustomConfig: '/custom/queryCustomConfig',

        // 执行之后 列表部分接口
        // 列头
        queryTitleConfig: '/custom/queryTitleConfig',
        // 数据
        queryCustomData: '/custom/queryCustomData'
      },
      allTreeKeys: [],
      departTree: [],
      treeLoading: false,
      disableMixinCreated: true,
      // 拖拽
      tempdata: {},

      // 树切换
      TreeSwitching: false,
      Datarelate: [],
      primaryFiled: '',
      subFiled: ''
    }
  },
  mounted() {
    this.loadTree()
    this.getHistoryConfig()
    this.changeStep(3, false)
    this.changeStep(4, false)
  },
  computed: {
    subTitles() {
      let titles = []
      this.subTableData.map(item => {
        if (item.data.title) titles.push(item.data.title)
      })
      return titles.toString()
    }
  },
  methods: {
    onReset() {
      // 重置
      this.primaryData = this.$options.data().primaryData
      this.subTableData = this.$options.data().subTableData
      this.IndicatorDataSource = []
      this.cacheIndicatorDataSource = []
      this.OutputDataSource = []
      this.cacheOutputDataSource = []
      this.Datarelate = []
      this.primaryFiled = ''
      this.subFiled = ''
      this.changeStep(0, false)
      this.changeStep(1, false)
      this.changeStep(2, false)
    },
    changeStep(index, flag) {
      setTimeout(() => {
        this.$emit('changStep', { index, flag })
      }, 0)
    },
    onSave() {
      if (this.primaryData.isEmpty) {
        this.$message.error('请配置审计资产主表')
        return
      }
      this.SaveOrRun('0')
    },
    onRun() {
      if(this.$route.query.typeValue) {
        this.$emit('toRun');
        return
      }
      // const { isReset, typeValue } = this.$route.query;
      // if(isReset && typeValue) {
      //   this.$router.push('/sj/mxpz/bmsjkhsp/implement?typeValue=' + typeValue + '&isReset=' + isReset);
      // }else {
      //   this.$router.push('/sj/mxpz/bmsjkhsp/implement');
      // }
      // return
      let flag = true
      if (this.primaryData.isEmpty) {
        this.$message.error('请配置审计资产主表')
        flag = false
      }
      if (this.Datarelate.length <= 0) {
        flag = false
        this.$message.error('请配置审计资产主表和附表关联为空')
      }
      if (this.IndicatorDataSource.length <= 0) {
        flag = false
        this.$message.error('请配置指标参数')
      }
      if (this.OutputDataSource.length <= 0) {
        flag = false
        this.$message.error('请配置输出指标')
      }
      if (flag) {
        this.SaveOrRun('1')
      }
    },
    handleOk(relate) {
      relate.map(item => {
        if (item.type == 1) {
          this.primaryFiled = item.linkField
        } else {
          this.subFiled += item.linkField
        }
      })
      this.Datarelate = [...relate]
    },
    // 查询配置
    getHistoryConfig() {
      this.onReset()
      getAction(this.url.queryCustomConfig)
        .then(result => {
          //  output:输出指标 , param:指标参数  ,relate:表关联，table：主表附表
          let { ifExe, output, param, relate, table } = result.result
          this.$emit('changeflag')
          if (ifExe == 1 && !this.isReset) {
            //   干别的事
            this.$emit('CheckResult')
          } else {
            this.IndicatorDataSource = [...param]
            this.changeStep(1, this.IndicatorDataSource.length > 0)
            // 缓存
            this.cacheIndicatorDataSource = [...param]
            this.OutputDataSource = [...output]
            this.changeStep(2, this.OutputDataSource.length > 0)
            // 缓存
            this.cacheOutputDataSource = [...output]
            //  主表附表关联字段
            this.handleOk(relate)

            // 主、附表关系
            let primaryTabel = table.find(item => item.type == 1)
            if (primaryTabel) {
              this.primaryData.data = {
                gatherNum: primaryTabel.gatherNum,
                gatherTimes: primaryTabel.gatherTimes,
                key: primaryTabel.id,
                lastGatherTime: primaryTabel.lastGatherTime,
                title: primaryTabel.tableNameText,
                tableName: primaryTabel.tableName,
                type: 1
              }
              this.primaryData.isEmpty = false
              this.changeStep(0, true)
            } else {
              this.primaryData.data = {}
              this.primaryData.isEmpty = true
              this.changeStep(0, false)
            }
            let subTbale = table.filter(item => item.type != 1)
            subTbale.map((item, index) => {
              this.subTableData[index].data = {
                gatherNum: item.gatherNum,
                gatherTimes: item.gatherTimes,
                key: item.id,
                lastGatherTime: item.lastGatherTime,
                title: item.tableNameText,
                tableName: item.tableName,
                type: 2
              }
              this.subTableData[index].isEmpty = false
            })
          }
        })
        .catch(err => {})
    },
    SaveOrRun(ifExe = '0') {
      let data = {
        table: [
          {
            ...this.primaryData.data,
            ifExe
          }
        ],
        param: [...this.IndicatorDataSource],
        output: [...this.OutputDataSource],
        relate: JSON.stringify(this.Datarelate)
      }
      this.subTableData.map(item => {
        if (!item.isEmpty)
          data.table.push({
            ...item.data,
            ifExe
          })
      })
      postAction(this.url.saveCustom, { data }).then(res => {
        if (res.success) {
          this.$message.success(res.result)
          if (ifExe == '0') {
            this.changeStep(3, true)
          } else {
            this.changeStep(4, true)
          }
          this.getHistoryConfig()
        } else {
          this.$message.error(res.result)
        }
      })
    },
    handlerClick() {
      let TabData = [{ ...this.primaryData.data }]
      this.subTableData.map(item => {
        if (Object.keys(item.data).length > 0) {
          TabData.push({ ...item.data })
        }
      })
      if (Object.keys(TabData[0]).length > 0)
        this.$refs.CheckOrganModal.showTabsTable(TabData, '审计资产关联', this.Datarelate)
      else this.$message.warning('请选择审计资产')
    },
    loadTree() {
      var that = this
      that.departTree = []
      this.treeLoading = true
      getAction(this.url.treeUrl).then(res => {
        if (res.success) {
          this.departTree = this.getTree(res.result)
          this.treeLoading = false
        }
      })
    },
    getTree(treeData, pid) {
      let treeArr = []
      for (let i = 0; i < treeData.length; i++) {
        let node = treeData[i]
        let newNode = {
          title: node.modelName,
          key: node.id,
          pid: node.pid,
          gatherNum: node.gatherNum,
          gatherTimes: node.gatherTimes,
          lastGatherTime: node.lastGatherTime,
          tableName: node.changeName,
          children: this.getTree(node.children, node.id)
        }
        treeArr.push(newNode)
      }
      return treeArr
    },
    // 删除itemBox内容
    handleDelete(isPrimary, key) {
      this.handleSwich()
      this.changeStep(3, false)
      if (isPrimary) {
        // 删除 列表中包含主表元素
        this.DeleteTableData(this.primaryData.data.tableName)
        //  主表
        this.primaryData.data = {}
        this.primaryData.isEmpty = true

        //修改steps 状态
        this.changeStep(0, false)
      } else {
        this.subTableData.map(item => {
          if (item.data.key == key) {
            // 删除 列表中包含主表元素
            this.DeleteTableData(item.data.tableName)
            item.data = {}
            item.isEmpty = true
          }
        })
      }
    },
    DeleteTableData(tableName) {
      //  指标表
      this.IndicatorDataSource = this.IndicatorDataSource.filter(item => item.tableName != tableName)
      this.cacheIndicatorDataSource = [...this.IndicatorDataSource]
      this.changeStep(1, this.IndicatorDataSource.length > 0)

      //   输出
      this.OutputDataSource = this.OutputDataSource.filter(item => item.tableName != tableName)
      this.cacheOutputDataSource = [...this.OutputDataSource]
      this.changeStep(2, this.OutputDataSource.length > 0)
    },
    // 拖拽---逻辑
    handledragstart({ event, node }) {
      console.log('树节点 拖拽开始')
      let el = event.target
      setTimeout(() => {
        el.classList.add('a')
      })
      if (!this.TreeSwitching) {
        // 原始树--使用这个存储
        let { gatherNum, gatherTimes, key, lastGatherTime, pid, title, tableName } =
          node.$options && node.$options.propsData.dataRef
        // 中间存储变量
        this.tempdata = {
          gatherNum,
          gatherTimes,
          key,
          lastGatherTime,
          pid,
          title,
          tableName
        }
      } else {
        //  表查的树
        let { title, key, sourceTableName, fieldEnName } = node.$options && node.$options.propsData.dataRef
        // 中间存储变量
        this.tempdata = {
          title,
          key,
          sourceTableName,
          fieldEnName
        }
      }
      event.dataTransfer.effectAllowed = 'move'
    },
    //  item-box拖拽接收数据
    dropHandler(e, type, index) {
      console.log(this.tempdata, 'tempdata')
      if (this.TreeSwitching) {
        this.$message.error('当前树形数据不可用')
        return
      }
      this.changeStep(3, false)
      if (type == 1) {
        // 主表数据
        this.primaryData.data = { ...this.tempdata, type: 1 }
        //  状态
        this.primaryData.isEmpty = false

        //修改steps 状态
        this.changeStep(0, true)
      } else if (type == 2) {
        //  去重
        this.subTableData.map(item => {
          if (item.data.key == this.tempdata.key) {
            item.data = {}
            item.isEmpty = true
          }
        })
        //   附表
        this.subTableData[index].data = { ...this.tempdata, type: 2 }
        this.subTableData[index].isEmpty = false
      }
      //  清空拖拽缓存数据
      this.tempdata = {}
    },
    // 指标参数表 拖拽接收数据
    DropHandler(targetData, cacheData) {
      console.log(this[targetData], cacheData, 'DropHandler')
      //  去重
      let result = this[targetData].find(item => item.id == this.tempdata.key)
      if (!result && this.TreeSwitching) {
        if (targetData.indexOf('IndicatorDataSource') != -1) {
          this[targetData].push({
            id: this.tempdata.key,
            tableName: this.tempdata.sourceTableName,
            fieldName: this.tempdata.fieldEnName,
            name: this.tempdata.title,
            logic: '',
            param: ''
          })
        } else {
          this[targetData].push({
            id: this.tempdata.key,
            tableName: this.tempdata.sourceTableName,
            fieldCnName: this.tempdata.title,
            fieldEnName: this.tempdata.fieldEnName
          })
        }
        this[cacheData] = [...this[targetData]]
      } else if (result) {
        this.$message.warning('指标参数重复')
      } else {
        this.$message.error('当前树形数据不可用')
      }
      // 更改setps状态
      if (this[targetData].length > 0) {
        if (targetData.indexOf('IndicatorDataSource') != -1) {
          this.changeStep(1, true)
        } else {
          this.changeStep(2, true)
        }
      }
      this.changeStep(3, false)
      this.tempdata = {}
    },
    dragoverHandler(ev) {
      ev.dataTransfer.dropEffect = 'move'
    },
    // 拖拽代码结束
    // itemBox  查看结构
    handleStructureCheck(tableName, modelName) {
      this.$refs.CheckOrganModal.show({ tableName }, modelName)
    },
    //  Item 数据查看
    handleDataCheck(tableName) {
      getAction(this.url.DataRelation, { tableName }).then(res => {
        if (res.success && res.result.length) {
          this.$router.push({
            path: '/sjxmzygl/yzzx/sbwzyz',
            query: {
              ...res.result[0]
            }
          })
        }
      })
    },
    // 表查树
    handleTreeCheck(tableName) {
      if (this.primaryData.isEmpty) {
        this.$message.warning('请选择审计资产主表')
        return
      }
      this.TreeSwitching = true
      this.treeLoading = true
      this.departTree = []
      getAction(this.url.DataStructure, { tableName }).then(res => {
        if (res.success) {
          this.departTree = res.result.map(item => {
            return {
              title: item.fieldCnName,
              key: item.fieldEnName,
              sourceTableName: item.sourceTableName,
              fieldEnName: item.fieldEnName
            }
          })
        } else {
          this.$message.error(res.message)
        }

        this.treeLoading = false
      })
    },
    // 切换树
    handleSwich() {
      this.loadTree()
      this.TreeSwitching = false
    },

    // 表格编辑部分
    handleEdit(targetData, id) {
      this.changeStep(3, false)
      const newData = [...this[targetData]]
      const target = newData.find(item => id === item.id)
      if (target) {
        target.editable = true
        this[targetData] = newData
      }
      console.log(this[targetData])
    },
    handleDataChange(targetData, id, value, col) {
      this.changeStep(3, false)
      const newData = [...this[targetData]]
      const target = newData.find(item => id === item.id)
      if (target) {
        target[col] = value
        this[targetData] = newData
      }
    },
    handleDeleteRow(targetData, id) {
      this.changeStep(3, false)
      const dataSource = [...this[targetData]]
      this[targetData] = dataSource.filter(item => item.id !== id)
      // 更改setps状态
      if (targetData.indexOf('IndicatorDataSource') != -1) {
        this.changeStep(1, this[targetData].length > 0)
      } else {
        this.changeStep(2, this[targetData].length > 0)
      }
    },
    handleSaveData(targetData, cacheData, id) {
      this.changeStep(3, false)
      const newData = [...this[targetData]]
      const newCacheData = [...this[cacheData]]
      const target = newData.find(item => id === item.id)
      const targetCache = newCacheData.find(item => id === item.id)
      if (target && targetCache) {
        delete target.editable
        this[targetData] = newData
        Object.assign(targetCache, target)
        this[cacheData] = newCacheData
      }
    },
    handleCancelData(targetData, cacheData, id) {
      this.changeStep(3, false)
      const newData = [...this[targetData]]
      const target = newData.find(item => id === item.id)
      if (target) {
        Object.assign(
          target,
          this[cacheData].find(item => id === item.id)
        )
        delete target.editable
        this[targetData] = newData
      }
    },
    handleUp(targetData, id) {
      this.changeStep(3, false)
      let index = this[targetData].findIndex(item => item.id === id)
      if (index > 0) {
        this[targetData][index] = this[targetData].splice(index - 1, 1, this[targetData][index])[0]
      } else {
        this.$message.warning('当前已经为第一条')
      }
    },
    handleDown(targetData, id) {
      this.changeStep(3, false)
      let index = this[targetData].findIndex(item => item.id === id)
      if (this[targetData].length - 1 > index) {
        this[targetData][index + 1] = this[targetData].splice(index, 1, this[targetData][index + 1])[0]
      } else {
        this.$message.warning('当前已经为最后一条')
      }
    }
  }
}
</script>

<style lang="less" scoped>
@import '~@assets/less/tableTheme.less';
.cogfig-box {
  max-height: 650px;
  overflow-y: scroll;
}
.br {
  border-radius: 20px;
}
.mh {
  min-height: 650px;
  max-height: 650px;
  overflow: auto;
}
.title-control {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.audit-box {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  .primary-table {
    width: 221px;
    height: 220px;
    box-sizing: border-box;
    padding: 10px;
    box-shadow: 0px 0px 8px #9ba9d0;
    border: 1px dashed #9ba9d0;
    border-radius: 20px;
    overflow: hidden;
    .primary-empty {
      border: 1px solid #3d58a8;
      border-bottom-width: 2px;
    }
  }
  .relative1 {
    width: 130px;
    height: 40px;
    background-color: #fff;
    position: relative;
    transform-style: preserve-3d;
    z-index: 8;
    .title-box {
      position: relative;
      z-index: 9;
      width: 100px;
      height: 100px;
      background-color: #3770b7;
      left: 50%;
      transform: translate(-50%, -30%);
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 8px;
      cursor: pointer;
      .box-card-title {
        color: #fff;
        font-size: 14px;
        font-weight: 600;
        display: inline-block;
        min-height: 20px;
        width: 100%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        letter-spacing: 1px;
      }
      .swap {
        transform: rotate(90deg);
        color: #fff;
      }
    }
    &::after,
    &::before {
      content: '';
      display: flex;
      height: 100px;
      width: 10px;
      position: absolute;
      border: 6px solid #163966;
      border-top-color: transparent;
      border-bottom-color: transparent;
      border-top-width: 32px;
      border-bottom-width: 32px;
      transform: translateZ(-1px);
      z-index: -1;
    }
    &::before {
      border-left-color: transparent;
      left: 2%;
      top: -77%;
    }
    &::after {
      border-right-color: transparent;
      left: 88%;
      top: -76%;
    }
  }
  .sub-table {
    height: 220px;
    width: 860px;
    box-sizing: border-box;
    padding: 10px 10px;
    border: 1px dashed #9ba9d0;
    box-shadow: 0px 0px 8px #9ba9d0;
    border-radius: 15px;
    background-color: #f9fdff;
    display: grid;
    // grid-template-columns: repeat(4, 1fr);
    grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr) minmax(0, 1fr);
    gap: 10px;
    .sub-empty {
      border: 1px dashed #3d58a8;
      overflow: hidden;
    }
  }
}

.button-control {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px 0px;
}
.yellow_search_btn {
  background-color: #ef9425b6;
  margin-left: 18px;
  color: white !important;
  font-size: 700;
}
.yellow_search_btn:hover {
  background-color: #ef9425f8;
}
</style>
